package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.cache.anno.GmallCache;
import com.atguigu.gmall.item.vo.CategoryView;
import com.atguigu.gmall.product.entity.BaseCategory1;
import com.atguigu.gmall.product.mapper.BaseCategory1Mapper;
import com.atguigu.gmall.product.service.BaseCategory1Service;
import com.atguigu.gmall.product.vo.CategoryVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BaseCategory1ServiceImpl extends ServiceImpl<BaseCategory1Mapper , BaseCategory1> implements BaseCategory1Service {

    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper ;

    private static final ConcurrentHashMap<String , List<CategoryVo>> LOCAL_CACHE = new ConcurrentHashMap<>() ;

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @GmallCache(cacheKey = "gmall:category" , timeout = 7 , timeUnit = TimeUnit.DAYS)
    @Override
    public List<CategoryVo> findAllCategory() {
        return baseCategory1Mapper.findAllCategory();
    }

    public List<CategoryVo> findAllCategoryLocalCache() {

        // 查询缓存
        List<CategoryVo> categoryVoList = LOCAL_CACHE.get("gmall:category");
        if(!CollectionUtils.isEmpty(categoryVoList)) {
            log.info("从缓存中查询到了数据...");
            return categoryVoList ;
        }


        List<CategoryVo> category = baseCategory1Mapper.findAllCategory();
        log.info("从数据库中查询到了数据...");
        LOCAL_CACHE.put("gmall:category" , category) ;

        // 返回
        return category;
    }

    @Override
    public CategoryView findCategoryViewBySkuId(Long skuId) {
        return baseCategory1Mapper.findCategoryViewBySkuId(skuId);
    }

}
